<!--
 * @Author: your name
 * @Date: 2021-04-13 16:42:43
 * @LastEditTime: 2021-07-27 11:11:20
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \dolphin-data-center-front-end\src\pages\quickEntry\projectManagement.vue
-->
<template>
  <page-layout title="项目管理">
    <div>
      <a-row style="background: #fff; padding: 20px">
        <a-row type="flex" justify="space-between">
          <div style="margin-bottom: 20px">
            <a-radio-group :value="headTabIndex" @change="onTabList">
              <a-radio-button v-for="(item, index) in headTabList" :key="item.txt" :value="index">
                {{ item.txt }}
                <span v-if="item.total!=null">({{ item.total }})</span>
              </a-radio-button>
            </a-radio-group>
          </div>
          <a-form layout="inline">
            <a-form-item label="项目负责人">
              <a-input style="width: 200px" v-model="pageListState.orgUserName" placeholder="请输入项目负责人名字" allow-clear>
                <a-icon slot="prefix" type="user" />
              </a-input>
            </a-form-item>
            <a-form-item label="项目名称">
              <a-input style="width: 200px" v-model="pageListState.projectName" placeholder="请输入项目名称" allow-clear>
                <a-icon slot="prefix" type="user" />
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="onSearch">
                <a-icon type="search" />
                查询
              </a-button>
            </a-form-item>
          </a-form>
        </a-row>
        <a-table class="employees-table" :columns="columns" :data-source="dataSource" :scroll="{x:true}" rowKey="id" :pagination="{
                        current: pageListState.page,
                        pageSize: pageListState.size,
                        total: total,
                        showLessItems: true,
                        onChange: onPageChange,
                    }">
          <div slot="status" slot-scope="text, record">
            <a-badge v-if="record.status == 'RUNNING'" color="green" text="已生效" />
            <a-badge v-else-if="record.status == 'TERMINATED'" color="red" text="已终止" />
            <a-badge v-else-if="record.status == 'RENEWAL'" color="gold" text="续签中" />
          </div>
          <span slot="advanceDay" slot-scope="text" v-if="text">每月{{ text }}号</span>
          <div slot="operation" slot-scope="text, record">
            <a class="ant-dropdown-link" @click="onDetail(record.id)">详情</a>
          </div>
        </a-table>
      </a-row>
      <drawer title="项目详情" ref="drawer" :visible.sync="detailDrawer" @getList="getList">
        <div slot="content">
          <div>
            <h3>{{ nowProjectHead.name }}</h3>
            <span>{{ nowProjectHead.contractType == 'waibao' ? '外包' : nowProjectHead.contractType == 'paiqian' ? '派遣' : nowProjectHead.contractType == 'renshidaili' ? '人事代理' : '' }}{{ nowProjectHead.contractType ? ',' : '' }}{{ nowProjectHead.advanceIf ? '垫付' : '不垫付' }}</span>
          </div>
          <a-descriptions class="stastistic-head" title=" " layout="vertical" bordered :column="5">
            <a-descriptions-item v-for="(value,key) in headStatistic" :key="key">
              <p>{{['当前状态','所属部门','负责人','开始时间','结束时间'][['status','deptName','orgUserName','contractBeginDateStr','contractEndDateStr'].findIndex(item=>item==key)]}}</p>
              <h3 v-if="key=='status'" class="status-text">
                <a-badge v-if="value == 'RUNNING'" color="green" text="已生效" />
                <a-badge v-else-if="value == 'TERMINATED'" color="red" text="已终止" />
                <a-badge v-else-if="value == 'RENEWAL'" color="gold" text="续签中" />
              </h3>
              <h3 style="height:25px" v-else>{{value?value:'  '}}</h3>
            </a-descriptions-item>
          </a-descriptions>
          <div style="margin:22px 0">
            <a-icon type="sound" theme="filled" style="color: #faad14" />
            项目配置：
            <a-space :size="15">
              <span v-for="(tab, index) in tabsList" :key="index">
                {{ tab.txt }}
                <span :style="!tab.status ? 'color:#FAAD14' : 'color:#52C41A'">{{ !tab.status ? '待完善' : '已完善' }}</span>
              </span>
            </a-space>
          </div>
          <div>
            <a-tabs :default-active-key="tabsIndex" @change="onTabsChange">
              <a-tab-pane v-for="(tab, index) in tabsList" :key="index" :tab="tab.txt"></a-tab-pane>
            </a-tabs>
            <Tab1 :basicInfoList="basicInfoList" :advanceDay="advanceDay" :editSuccess="editSuccess" :financialInfoList="financialInfoList" @info-type="onInfoAgain" @dateChange="onDateChange" @changeDept="onChangeDept" @changeAdvanceIf="onChangeAdvanceIf" @basicInfo="onBasicInfo" @financialInfo="onFinancialInfo" v-if="tabsIndex === 0" />
            <Tab2 :memberList="memberList" @isMeberModal="onMemberModal" @delMember="onDelMember" v-if="tabsIndex === 1" />
            <Tab3 :basicInfoConfig="projectConfigList" @checkChange="onCheckChange" v-if="tabsIndex === 2" />
            <Tab4 :configSuccess='configSuccess' v-if="tabsIndex === 3" :config="projectConfig" :initProjectConfig="initProjectConfig" @update-config="onUpdateConfig" />
          </div>
        </div>
      </drawer>
      <!-- tab2 添加人员弹窗 -->
      <memberModal :memberModal="memberModal" :delPostCode="delPostCode" :havePostList="havePostList" :addMemberState="addMemberState" :memberList="allMemberList" @cancelModal="cancelMemberModal" @changeUser="onChangeUser" @changePost="onChangePost" :z-index="99"></memberModal>
    </div>
  </page-layout>
</template>

<script>
import Tab1 from './tabs/tab1';
import Tab2 from './tabs/tab2';
import Tab3 from './tabs/tab3';
import Tab4 from './tabs/tab4';
import memberModal from './modal/projectDetailAddMemberModal';
import PageLayout from '@/layouts/PageLayout';
import Drawer from '@/pages/components/drawer'
import { getObjToArray } from '@/utils/util';
import { getPageList, getHeadInfo, getBaseInfo, getFinanceInfo, getMemberInfo, getCareerField, getUpdateProjectConfig, getDelMember, getUpdateBasicInfo, getUpdateFinanceInfo, getAddOrUpdateMember, getProjectConfig, getUpdateConfig } from '@/services/project';
export default {
  name: 'projectManagement',
  components: { Tab1, Tab2, Tab3, Tab4, memberModal, PageLayout, Drawer },
  data () {
    return {
      detailDrawer: false,
      delPostCode: undefined,
      advanceDay: null,
      projectId: '',
      nowProjectHead: {},
      headStatistic: {},
      addMemberState: {
        name: '',
        postCheckedList: [],
      },
      headTabList: [
        { txt: '全部', total: null },
        { txt: '信息待完善', total: null },
        { txt: '成员待分配', total: null },
      ],
      addUserId: null,
      allMemberList: [],
      tabsIndex: 0,
      pageListState: {
        page: 1,
        size: 10,
        projectName: '',
        orgUserName: '',
        projectInfoFullIf: null,
        projectMemberFullIf: null,
      },
      headTabIndex: 0,
      total: 0,
      columns: [
        {
          title: '项目ID',
          dataIndex: 'id',
          width: 80,
          fixed: 'left',
        },
        {
          title: '企业名称',
          dataIndex: 'companyName',
          width: 260,
          fixed: 'left',
        },
        {
          title: '项目名称',
          dataIndex: 'name',
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '所属部门',
          dataIndex: 'deptName',
        },
        {
          title: '项目负责人',
          dataIndex: 'orgUserName',
        },
        {
          title: '客户付款截止日期',
          dataIndex: 'advanceDay',
          scopedSlots: { customRender: 'advanceDay' },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 100,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      dataSource: [],
      tabsList: [
        {
          txt: '基本信息',
          status: false,
        },
        {
          txt: '成员列表',
          status: false,
        },
        {
          txt: '入职登记表字段配置',
          status: false,
        },
        {
          txt: '项目配置',
          status: false,
        },
      ],
      basicInfoList: [],
      financialInfoList: [],
      initBasicInfoList: [],
      initFinancialInfoList: [],
      memberList: [],
      memberModal: false,
      projectConfigList: [],
      projectConfig: {},
      initProjectConfig: {},
      havePostList: [],
      editSuccess: null,
      configSuccess: 1
    };
  },
  methods: {
    onInfoAgain (i) {
      const initFinancialInfoList = this.$Storage.get('initFinancialInfoList');
      const initBasicInfoList = this.$Storage.get('initBasicInfoList');
      if (i == 1) {
        this.financialInfoList = initFinancialInfoList
      } else {
        this.basicInfoList = initBasicInfoList
      }
    },
    onTabList (e) {
      var index = e.target.value;
      this.headTabIndex = index;
      if (this.headTabIndex == 0) {
        this.pageListState.projectInfoFullIf = null;
        this.pageListState.projectMemberFullIf = null;
      } else if (this.headTabIndex == 1) {
        this.pageListState.projectInfoFullIf = false;
        this.pageListState.projectMemberFullIf = null;
      } else if (this.headTabIndex == 2) {
        this.pageListState.projectMemberFullIf = false;
        this.pageListState.projectInfoFullIf = null;
      }
      this.getPageList(this.pageListState);
    },
    onMemberModal (result) {
      this.memberModal = result;
    },
    onDetail (id) {
      this.detailDrawer = true;
      this.projectId = id;
      const params = { projectId: this.projectId };
      this.getHeadInfo(params);
      this.getBaseInfo(params);
      this.getFinanceInfo(params);
      this.getMemberInfo(params);
      this.getCareerField(params);
      this.getProjectConfig(params);
      this.tabsIndex = 0
    },
    onSearch () {
      this.getPageList(this.pageListState);
    },
    getList () {
      this.getPageList(this.pageListState);
    },
    onTabsChange (index) {
      this.tabsIndex = index;
      const params = { projectId: this.projectId };
      if (this.tabsIndex == 0) {
        this.getBaseInfo(params);
        this.getFinanceInfo(params);
      } else if (this.tabsIndex == 1) {
        this.getMemberInfo(params);
      } else if (this.tabsIndex == 2) {
        this.getCareerField(params);
      } else if (this.tabsIndex == 3) {
        this.getProjectConfig(params);
      }
    },
    cancelMemberModal (result) {
      let { str, data } = result;
      if (str == 'ok') {
        this.addMemberState = data;
        const params = {
          orgUserId: this.addUserId,
          projectId: this.projectId,
          postCodeList: this.addMemberState.postCheckedList.map(Number),
        };
        this.havePostList = this.havePostList.concat(this.addMemberState.postCheckedList.map(Number));
        this.getAddOrUpdateMember(params);
      } else {
        this.addMemberState.name = '';
      }
      this.memberModal = false;
    },
    /**
     * @description: 分页
     * @param {*} pageListState.page
     * @param {*} pageListState.size
     * @return {*}
     */
    onPageChange (page, size) {
      this.pageListState.page = page;
      this.pageListState.size = size;
      this.getPageList(this.pageListState);
    },
    /**
     * @description: 分页列表
     * @param {*}
     * @return {*}
     */
    getPageList (params) {
      getPageList(params).then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          this.dataSource = data.pageList.content;
          this.total = data.pageList.totalElements;
          this.headTabList[1].total = data.perfectFalseCount
          this.headTabList[2].total = data.memberFullFalseCount
        } else {
          this.$message.error(msg);
        }
      });
    },
    /**
     * @description: 项目详情-头部信息
     * @param {*}
     * @return {*}
     */
    getHeadInfo (params) {
      getHeadInfo(params).then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          this.nowProjectHead = data;
          let { status, deptName, orgUserName, contractBeginDateStr, contractEndDateStr } = this.nowProjectHead
          this.headStatistic = { status, deptName, orgUserName, contractBeginDateStr, contractEndDateStr }
          this.tabsList[0].status = this.nowProjectHead.projectBaseInfoFullIf;
          this.tabsList[1].status = this.nowProjectHead.projectMemberInfoFullIf;
          this.tabsList[2].status = this.nowProjectHead.projectEntryFieldInfoFullIf;
          this.tabsList[3].status = this.nowProjectHead.projectConfigFullIf;
        } else {
          this.$message.error(msg);
        }
      });
    },
    /**
     * @description: 项目详情-基本信息
     * @param {*}
     * @return {*}
     */
    getBaseInfo (params) {
      getBaseInfo(params).then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          this.basicInfoList = this.getBasicInfoArray(data);
          this.$Storage.set('initBasicInfoList', this.getBasicInfoArray(data));
        } else {
          this.$message.error(msg);
        }
      });
    },
    /**
     * @description: 对象与数组互转-基本信息/财务信息
     * @param {*}
     * @return {*}
     */
    getBasicInfoArray (obj) {
      const arr1 = ['企业名称', '项目名称', '项目类型', '所属部门', '签约主体', '运营公司', '合同开始日期', '合同终止日期', '服务费'];
      const arr2 = ['companyName', 'projectName', 'projectType', 'deptName', 'signName', 'orgDeptName', 'contractBeginDateStr', 'contractEndDateStr', 'serviceAmt']
      return getObjToArray(arr1, arr2, obj)
    },
    getFinanceInfoArray (obj) {
      const arr1 = ['客户开票单位', '纳税人识别号', '银行账号', '开户银行', '开户支行', '电话', '地址', '费用收取方式', '工资发放日', '账单日', '是否垫付', '垫付收款日', '到付日'];
      const arr2 = ['invoiceName', 'taxpayerNumber', 'bankNum', 'bankName', 'bankDeposit', 'phone', 'address', 'chargeType', 'salaryDay', 'billingDay', 'advanceIf', 'advanceDay', 'arrivalDay']
      return getObjToArray(arr1, arr2, obj)
    },
    getBasicInfoObject (arr) {
      var obj = {};
      arr.forEach(val => {
        obj[
          ['companyName', 'projectName', 'projectType', 'deptName', 'signName', 'orgDeptName', 'contractBeginDateStr', 'contractEndDateStr', 'serviceAmt'][
          ['企业名称', '项目名称', '项目类型', '所属部门', '签约主体', '运营公司', '合同开始日期', '合同终止日期', '服务费'].findIndex(item => item == val.txt)
          ]
        ] = val.value;
      });
      return obj;
    },
    getFinanceInfoObject (arr) {
      var obj = {};
      arr.forEach(val => {
        obj[
          ['invoiceName', 'taxpayerNumber', 'bankNum', 'bankName', 'bankDeposit', 'phone', 'address', 'chargeType', 'salaryDay', 'billingDay', 'advanceIf', 'advanceDay', 'arrivalDay'][
          ['客户开票单位', '纳税人识别号', '银行账号', '开户银行', '开户支行', '电话', '地址', '费用收取方式', '工资发放日', '账单日', '是否垫付', '垫付收款日', '到付日'].findIndex(item => item == val.txt)
          ]
        ] = val.value;
      });
      return obj;
    },
    /**
     * @description: 项目详情-财务信息
     * @param {*}
     * @return {*}
     */
    getFinanceInfo (params) {
      getFinanceInfo(params).then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          const arr = this.getFinanceInfoArray(data);
          this.advanceDay = arr[11].value
          if (!arr[10].value) {
            arr.splice(11, 1);
          }
          this.$Storage.set('initFinancialInfoList', arr);
          this.financialInfoList = arr;
        } else {
          this.$message.error(msg);
        }
      });
    },
    /**
     * @description: 项目详情-成员信息
     * @param {*}
     * @return {*}
     */
    getMemberInfo (params) {
      getMemberInfo(params).then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          this.memberList = data;
          this.havePostList = this.memberList.map(item => item.postCode);
        } else {
          this.$message.error(msg);
        }
      });
    },
    /**
     * @description: 项目详情-项目入职字段
     * @param {*}
     * @return {*}
     */
    getCareerField (params) {
      getCareerField(params).then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          this.projectConfigList = data;
        } else {
          this.$message.error(msg);
        }
      });
    },
    /**
     * @description: 修改入职字段的值
     * @param {*}
     * @return {*}
     */
    onCheckChange (result) {
      let { checked, item, option } = result;
      item[option] = checked;
      const params = {
        id: item.id,
        editableIf: item.editableIf,
        requiredIf: item.requiredIf,
        showIf: item.showIf,
      };
      this.getUpdateProjectConfig(params);
    },
    /**
     * @description: 更新入职字段
     * @param {*}
     * @return {*}
     */
    getUpdateProjectConfig (params) {
      getUpdateProjectConfig(params).then(res => {
        let { code, msg } = res.data;
        if (code != 200) {
          this.$message.error(msg);
        }
      });
    },
    /**
     * @description: 项目详情-删除项目成员
     * @param {*}
     * @return {*}
     */
    getDelMember (params) {
      getDelMember(params).then(res => {
        let { code, msg } = res.data;
        if (code == 200) {
          this.getMemberInfo({ projectId: this.projectId });
          const params = { projectId: this.projectId };
          this.getHeadInfo(params);
        } else {
          this.$message.error(msg);
        }
      });
    },
    onDelMember (res) {
      let { id, postCode } = res;
      this.delPostCode = postCode;
      const index = this.havePostList.findIndex(item => item == postCode);
      this.havePostList.splice(index, 1);
      this.getDelMember({ id });
    },
    /**
     * @description: 项目详情-编辑基本信息
     * @param {*}
     * @return {*}
     */
    getUpdateBasicInfo (params) {
      getUpdateBasicInfo(params).then(res => {
        let { code, msg } = res.data;
        if (code == 200) {
          const params = { projectId: this.projectId };
          this.getHeadInfo(params);
          this.editSuccess = true;
        } else {
          this.$message.error(msg);
        }
      });
    },
    onDateChange (data) {
      let { dateString, type } = data;
      this.basicInfoList.filter(val => val.txt == type)[0].value = dateString;
    },
    onChangeDept (value) {
      this.basicInfoList[3].value = value;
    },
    onBasicInfo (result) {
      this.editSuccess = null;
      const params = this.getBasicInfoObject(result);
      params.id = this.projectId;
      if (!params.contractBeginDateStr) {
        this.$message.warning('合同开始日期不允许为空！')
        return
      }
      if (!params.contractEndDateStr) {
        this.$message.warning('合同终止日期不允许为空！')
        return
      }
      var d1 = new Date(params.contractBeginDateStr.replace(/-/g, "/"));
      var d2 = new Date(params.contractEndDateStr.replace(/-/g, "/"));
      if (params.contractBeginDateStr && params.contractEndDateStr && d1 > d2) {
        this.$message.warning('开始时间不能大于结束时间！')
        return;
      }
      this.getUpdateBasicInfo(params);
    },
    /**
     * @description: 项目详情-编辑财务信息
     * @param {*}
     * @return {*}
     */
    getUpdateFinanceInfo (params) {
      getUpdateFinanceInfo(params).then(res => {
        let { code, msg } = res.data;
        if (code == 200) {
          this.editSuccess = true;
        } else {
          this.$message.error(msg);
        }
      });
    },
    onFinancialInfo (result) {
      this.editSuccess = null;
      const params = this.getFinanceInfoObject(result);
      params.id = this.projectId;
      this.getUpdateFinanceInfo(params);
    },
    onChangeAdvanceIf (value) {
      this.financialInfoList[10].value = value;
    },
    /**
     * @description: 项目详情-编辑成员信息
     * @param {*}
     * @return {*}
     */
    onChangeUser (result) {
      this.addMemberState.name = result[0];
      this.addUserId = result[1];
    },
    onChangePost (val) {
      this.addMemberState.postCheckedList = val;
    },
    getAddOrUpdateMember (params) {
      getAddOrUpdateMember(params).then(res => {
        let { code, msg } = res.data;
        if (code == 200) {
          this.getMemberInfo({ projectId: this.projectId });
          const params = { projectId: this.projectId };
          this.getHeadInfo(params);
        } else {
          this.$message.error(msg);
        }
      });
    },
    /**
     * @description: 获取项目配置
     * @param {*}
     * @return {*}
     */
    getProjectConfig (params) {
      getProjectConfig(params).then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          let tempConfig = {};
          tempConfig = data;
          if (!tempConfig.billGenDay) {
            tempConfig.billGenDay = undefined;
          }
          tempConfig.billMonth = tempConfig.billMonth ? tempConfig.billMonth.toString() : undefined;
          this.projectConfig = tempConfig;
          this.initProjectConfig = JSON.parse(JSON.stringify(this.projectConfig))
        } else {
          this.$message.error(msg);
        }
      });
    },
    /**
     * @description: 更新项目配置
     * @param {*}
     * @return {*}
     */
    getUpdateConfig (params) {
      getUpdateConfig(params).then(res => {
        let { code, msg } = res.data;
        if (code == 200) {
          this.configSuccess = 1
          this.$message.success('保存成功！');
        } else {
          this.configSuccess = 0
          this.$message.error(msg);
        }
      });
    },
    onUpdateConfig (data) {
      if (!data) {
        this.projectConfig = this.initProjectConfig;
        this.configSuccess = 1;
      } else {
        if (data === 'edit') {
          this.configSuccess = 0;
        } else {
          data.projectId = this.projectId;
          this.getUpdateConfig(data);
        }
      }
    },
  },
  mounted () {
    const type = window.location.href.split('=')[1];
    if (type == '') {
      this.pageListState.projectInfoFullIf = null;
      this.pageListState.projectMemberFullIf = null;
    } else if (type == 'projectInfoFullIf') {
      this.pageListState.projectInfoFullIf = false;
      this.pageListState.projectMemberFullIf = null;
    } else if (type == 'projectMemberFullIf') {
      this.pageListState.projectMemberFullIf = false;
      this.pageListState.projectInfoFullIf = null;
    }
    this.getPageList(this.pageListState);
  },
};
</script>

<style scoped lang="less">
.stastistic-head {
  height: 88px;
  /deep/ .ant-descriptions-item-content {
    padding: 16px !important;
    p,
    h3 {
      margin-bottom: 0 !important;
    }
    h3 {
      font-size: 20px !important;
    }
  }
  .status-text {
    /deep/ .ant-badge-status-text {
      font-size: 20px !important;
    }
  }
  /deep/.ant-descriptions-view {
    table tbody .ant-descriptions-row:first-child {
      display: none;
    }
  }
}
</style>
